package com.ruoyi.materialCuttingPlan.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.materialCuttingPlan.domain.McpMaterialResults;
import com.ruoyi.materialCuttingPlan.domain.McpProjects;
import com.ruoyi.materialCuttingPlan.domain.McpVariableValue;
import com.ruoyi.materialCuttingPlan.domain.McpWindows;
import com.ruoyi.materialCuttingPlan.service.IMcpMaterialResultsService;
import com.ruoyi.materialCuttingPlan.service.IMcpProjectsService;
import com.ruoyi.materialCuttingPlan.service.IMcpWindowsService;
import com.ruoyi.materialCuttingPlan.utils.CuttingPlanExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 门窗详细信息Controller
 *
 * @author ruoyi
 * @date 2025-07-05
 */
@RestController
@RequestMapping("/material-cutting-plan/windows")
@Validated
public class McpWindowsController extends BaseController {
    @Autowired
    private IMcpWindowsService mcpWindowsService;

    @Autowired
    private IMcpProjectsService mcpProjectsService;

    @Autowired
    private IMcpMaterialResultsService mcpMaterialResultsService;

//    @Autowired
//    private IMcpVariableValue mcpProjectsService;

    /**
     * 查询门窗详细信息列表
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:list')")
    @GetMapping("/list")
    public TableDataInfo list(McpWindows mcpWindows) {
        startPage();
        List<McpWindows> list = mcpWindowsService.selectMcpWindowsList(mcpWindows);
        return getDataTable(list);
    }

    /**
     * 导出门窗详细信息列表
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:export')")
    @Log(title = "门窗详细信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, McpWindows mcpWindows) {
        List<McpWindows> list = mcpWindowsService.selectMcpWindowsList(mcpWindows);
        ExcelUtil<McpWindows> util = new ExcelUtil<McpWindows>(McpWindows.class);
        util.exportExcel(response, list, "门窗详细信息数据");
    }

//    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:export')")
//    @Log(title = "门窗详细信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/exportById")
//    public void exportById(HttpServletResponse response, McpWindows mcpWindows) {
//        McpWindows mcpWindows1 = mcpWindowsService.selectMcpWindowsById(mcpWindows.getId());
//        McpProjects mcpProjects = mcpProjectsService.selectMcpProjectsById(mcpWindows1.getProjectId());
//        McpMaterialResults mcpMaterialResults = new McpMaterialResults();
//        mcpMaterialResults.setWindowId(mcpWindows1.getId());
//        List<McpMaterialResults> mcpMaterialResults1 = mcpMaterialResultsService.selectMcpMaterialResultsList(mcpMaterialResults);
//
//        Map<String, Object> projectInfo = new LinkedHashMap<>();
//        projectInfo.put("项目名称", mcpProjects.getProjectName());
//        projectInfo.put("项目地址", mcpProjects.getProjectAddress());
//        projectInfo.put("项目开始", "");
//        projectInfo.put("项目结束", "");
//        if (null != mcpProjects.getStartDate()) {
//            projectInfo.put("项目开始", DateUtils.parseDateToStr("yyyy-MM-dd", mcpProjects.getStartDate()));
//        }
//        if (null != mcpProjects.getEndDate()) {
//            projectInfo.put("项目结束", DateUtils.parseDateToStr("yyyy-MM-dd", mcpProjects.getEndDate()));
//        }
//        projectInfo.put("门窗类型", mcpWindows1.getTypeImage()); // 示例图片路径
//        projectInfo.put("高度", mcpWindows1.getHeight());
//        projectInfo.put("宽度", mcpWindows1.getWidth());
//        projectInfo.put("数量", mcpWindows1.getQuantity());
//
//        String windowTitle = mcpWindows1.getWindowsName();
//
//        List<Map<String, Object>> materialData = new ArrayList<>();
//        for (McpMaterialResults mcpMaterialResult : mcpMaterialResults1) {
//            Map<String, Object> material = new LinkedHashMap<>();
//            material.put("materialName", mcpMaterialResult.getMaterialName());
//            material.put("length", mcpMaterialResult.getMaterialLength());
//            material.put("quantity", mcpMaterialResult.getMaterialCount());
//            materialData.add(material);
//        }
//        //按照名称排序
//        materialData.sort(Comparator.comparing(o -> o.get("materialName").toString()));
//
//        try {
//            CuttingPlanExcelUtil.exportCuttingPlan(projectInfo, windowTitle, materialData, response);
//            System.out.println("导出成功！");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:export')")
    @Log(title = "门窗详细信息", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByIds")
    public void exportByIds(HttpServletResponse response, String ids) {
        String[] split = ids.split(",");
        Long[] split1 = new Long[split.length];
        for (int i = 0; i < split.length; i++) {
            split1[i] = Long.parseLong(split[i]);
        }
        List<McpWindows> mcpWindowss = mcpWindowsService.selectMcpWindowsByIds(split1);
        List<Long> collect = mcpWindowss.stream().map(McpWindows::getProjectId).distinct().collect(Collectors.toList());
        if (collect.size() > 1) {
            throw new BaseException("请选择相同项目！");
        }
        McpProjects mcpProjects = mcpProjectsService.selectMcpProjectsById(collect.get(0));


        List<List<McpMaterialResults>> mcpMaterialResults = new ArrayList<>();
        BigDecimal totalWeight = new BigDecimal(0);
        for (McpWindows mcpWindow : mcpWindowss) {
            McpMaterialResults mcpMaterialResult = new McpMaterialResults();
            mcpMaterialResult.setWindowId(mcpWindow.getId());
            List<McpMaterialResults> mcpMaterialResults1 = mcpMaterialResultsService.selectMcpMaterialResultsList(mcpMaterialResult);
            mcpMaterialResults.add(mcpMaterialResults1);
            List<McpVariableValue> mcpVariableValues = mcpWindowsService.selectMcpVariableValueList(mcpWindow.getId());
            mcpWindow.setMcpVariableValueList(mcpVariableValues);
            if (!mcpMaterialResults1.isEmpty()){
                for (int i = 0; i < mcpMaterialResults1.size(); i++) {
                    if (mcpMaterialResults1.get(i).getMaterialWeightPerMeter()!=null){
                        totalWeight = totalWeight.add(
                                mcpMaterialResults1.get(i).getMaterialWeightPerMeter()
                                        .multiply(new BigDecimal(mcpMaterialResults1.get(i).getMaterialCount().toString()))
                                        .multiply(mcpMaterialResults1.get(i).getMaterialLength()));
                    }
                }
            }
        }
        totalWeight = totalWeight.divide(new BigDecimal("1000"));
        String totalWeightString = totalWeight.stripTrailingZeros().toPlainString();
        try {
            CuttingPlanExcelUtil.exportCuttingPlan(mcpProjects, mcpWindowss, mcpMaterialResults, totalWeightString,response);
            System.out.println("导出成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取门窗详细信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(mcpWindowsService.selectMcpWindowsById(id));
    }

    /**
     * 新增门窗详细信息
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:add')")
    @Log(title = "门窗详细信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody McpWindows mcpWindows) {
        return toAjax(mcpWindowsService.insertMcpWindows(mcpWindows));
    }

    /**
     * 修改门窗详细信息
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:edit')")
    @Log(title = "门窗详细信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody McpWindows mcpWindows) {
        return toAjax(mcpWindowsService.updateMcpWindows(mcpWindows));
    }
//    /**
//     * 修改门窗详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:edit')")
//    @Log(title = "门窗详细信息", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody McpWindows mcpWindows)
//    {
//        return toAjax(mcpWindowsService.updateMcpWindows(mcpWindows));
//    }

    /**
     * 删除门窗详细信息
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:remove')")
    @Log(title = "门窗详细信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@Validated @PathVariable Long[] ids) {
        return toAjax(mcpWindowsService.deleteMcpWindowsByIds(ids));
    }

    /**
     * 计算门窗详细信息
     */
    @PreAuthorize("@ss.hasPermi('material-cutting-plan:windows:remove')")
    @Log(title = "门窗详细信息", businessType = BusinessType.UPDATE)
    @GetMapping("/calculate/{id}")
    public AjaxResult calculate(@PathVariable Long id) {
        return toAjax(mcpWindowsService.calculateMcpWindowsById(id));
    }
}
